<?php
/**
 * author      :chenwenwen
 * createTime  :2020-05-02 14:57
 * description :
 */

namespace app\common\business;

use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use app\common\lib\Str;

class User {
    public $userObj = null;

    public function __construct() {
        $this->userObj = new UserModel;
    }

    public function login($data = []) {
        $redis_code = cache(config('redis.sms_code_pre') . $data['phone_number']);
        if (empty($redis_code) || $redis_code != $data['code']) {
            //throw new \think\Exception('不存在该验证码', -1);
        }

        //判断用户记录是否存在 phone_number
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if (!$user) {
            //不存在则新增用户
            $userData = [
                'username' => 'wen-' . $data['phone_number'],
                'type' => $data['type'],
                'phone_number' => $data['phone_number'],
                'status' => config('status.mysql.table_normal'),
            ];
            $this->userObj->save($userData);
            $userId = $this->userObj->id;
            $username = $this->userObj->username;
        } else {
            //更新操作
            $userData = [];
            $userId = $user->id;
            $username = $user->username;
        }

        $cacheData = [
            'id' => $userId,
            'username' => $username
        ];
        $token = Str::getLoginToken($data['phone_number']);

        $res = cache(config('redis.token_pre') . $token, $cacheData, Time::userLoginExpireTime($data['type']));

        return $res ? ['token' => $token, 'username' => $username] : false;

    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id) {
        $user = $this->userObj->getUserById($id);
        //判断用户状态
        if (false === $user || $user->status != config('status.mysql.table_normal')) return [];

        return $user->toArray();
    }

    public function getNormalUserByUsername($username) {
        $user = $this->userObj->getUserByUsername($username);
        //判断用户状态
        if (!$user || $user->status != config('status.mysql.table_normal')) return [];

        return $user->toArray();
    }

    public function update($id, $data) {
        $user = $this->getNormalUserById($id);
        if(!$user) throw new \think\Exception('不存在该用户');
        //检查用户名是否存在
        $userRes = $this->getNormalUserByUsername($data['username']);
        if ($userRes && $id != $userRes['id']) throw new \think\Exception('该用户名已经存在，请重新设置');

        return $this->userObj->updateById($id, $data);
    }
}